package com.tailyou.hms.firstapp.act;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.tailyou.hms.firstapp.R;
import com.tailyou.hms.firstapp.receiver.DynamicReceiver;

public class ReceiverActivity extends AppCompatActivity {

    private DynamicReceiver dynamicReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiver);
        findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setPackage(getPackageName());
                intent.setAction("tailyou");
                intent.putExtra("msg", "内容");
                sendBroadcast(intent);
            }
        });
        findViewById(R.id.btnRegister).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Java代码中动态注册广播
                dynamicReceiver = new DynamicReceiver();
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("tailyou");
                registerReceiver(dynamicReceiver, intentFilter);
            }
        });
        findViewById(R.id.btnUnregister).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消注册广播
                if (dynamicReceiver != null)
                    unregisterReceiver(dynamicReceiver);
            }
        });
    }

}